import api from 'api'
import { parse } from 'query-string'
import { useState } from 'react'
import store from 'store'

import { history } from '@umijs/max'

const { userLogin, userCurrent } = api

export default function Login() {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const login = async ({ payload }: { payload: any }) => {
    setLoading(true)
    setError(null)
    try {
      // 账号密码登录
      const res = await userLogin({
        ...payload,
        code: '6666',
        appid: 'mara',
      })
      const { code, data } = res
      if (code === 200 && data.token) {
        store.set('token', data.token)
        //   yield put({ type: 'app/query' })
        //   yield take('app/query/@@end')
        const query = parse(history.location.search)
        const { from } = query as { from?: string }
        from ? (window.location.href = from) : (window.location.href = '/')
      } else {
        setError(data?.message || '登录失败')
      }
    } catch (error: any) {
      console.log(error)
      setError(error?.message || '登录失败')
    } finally {
      setLoading(false)
    }
  }

  // 检查用户是否已经登录
  const checkLoginStatus = async () => {
    try {
      const res = await userCurrent()
      if (res.code === 200) {
        store.set('current_user', res.data)
        return true
      } else {
        store.clearAll()
        return false
      }
    } catch (error) {
      store.clearAll()
      return false
    }
  }

  const signOut = () => {
    // 清除存储的用户信息
    store.clearAll()
    // 跳转到登录页
    history.push('/login')
  }

  const clearError = () => {
    setError(null)
  }

  return {
    login,
    loading,
    error,
    signOut,
    clearError,
    checkLoginStatus,
  }
}
